#!/usr/bin/env python3

import os
import shutil

import common
import shlex
from shell_helpers import LF

class Main(common.BuildCliFunction):
    def __init__(self):
        super().__init__(
            description='''\
https://cirosantilli.com/linux-kernel-module-cheat#dhrystone
'''
        )
        self._add_argument('--ccflags')
        self._add_argument('--force-rebuild')
        self._add_argument('--optimization-level')

    def setup(self, env):
        self.root_relpath = os.path.join('submodules', 'dhrystone')

    def build(self):
        build_dir = self.get_build_dir()
        cflags = ['-O{}'.format(self.env['optimization_level'])]
        extra_flags = []
        if self.env['static']:
            cflags.extend(['-static'])
        if self.env['force_rebuild']:
            extra_flags.extend(['-B', LF])
        if self.env['mode'] == 'baremetal':
            extra_objs = [
                self.env['baremetal_syscalls_obj'],
                self.env['baremetal_syscalls_asm_obj']
            ]
        else:
            extra_objs = []
        ret = self.sh.run_cmd(
            [
                'make', LF,
                '-j', str(self.env['nproc']), LF,
                '-C', os.path.join(self.env['submodules_dir'], 'dhrystone'), LF,
                'CC={}'.format(self.env['gcc_path']), LF,
                'CFLAGS={}'.format(' '.join(cflags)), LF,
                'EXTRA_OBJS={}'.format(' '.join(extra_objs)), LF,
                'OUT_DIR={}'.format(build_dir), LF,
            ]
            + extra_flags
        )
        if ret == 0 and self.env['mode'] == 'userland':
            self.sh.copy_file_if_update(
                os.path.join(build_dir, 'dhrystone'),
                os.path.join(self.env['out_rootfs_overlay_lkmc_dir'], self.root_relpath, 'dhrystone'),
            )
        return ret

    def get_build_dir(self):
        return os.path.join(self.env['build_dir'], self.root_relpath)

if __name__ == '__main__':
    Main().cli()
